package com.shishuo.cms.filter;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver;
import org.springframework.web.servlet.support.RequestContext;

import com.shishuo.cms.service.ConfigService;

public class CustomSimpleMappingExceptionResolver extends
		SimpleMappingExceptionResolver {
	private final Logger logger = Logger.getLogger(this.getClass());
	@Autowired
	private ConfigService configService;
	@Override
	protected ModelAndView doResolveException(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex){
		logger.error("异常日志拦截", ex);
		String viewName = determineViewName(ex, request);
		if (viewName != null) {// html格式返回
			if (!(request.getHeader("accept").indexOf("application/json") > -1 || (request
					.getHeader("X-Requested-With") != null && request
					.getHeader("X-Requested-With").indexOf("XMLHttpRequest") > -1))) {
				// 如果不是异步请求
				Integer statusCode = determineStatusCode(request, viewName);
				if (statusCode != null) {
					applyStatusCodeIfPossible(request, response, statusCode);
				}
				viewName="template/"+ configService.getConfigByKey("SYS_THEME")+"/"+viewName;
				request.setAttribute("statusCode", statusCode);
				request.setAttribute("exceptionMsg", getExceptionMsg(ex.getClass().getSimpleName(),request,ex.getMessage()));
				return getModelAndView(viewName, ex, request);
			} else {// JSON格式返回
				try {
					response.setContentType("text/html; charset=utf-8");
					PrintWriter writer = response.getWriter();
					writer.write(getExceptionMsg(ex.getClass().getSimpleName(),request,ex.getMessage()));//返回异常类型及其消息信息
					writer.flush();
				} catch (IOException e) {
					e.printStackTrace();
				}
				return null;
			}
		} else {
			return null;
		}
	}
	private String getExceptionMsg(String className,HttpServletRequest request,String exMessageCode){
			return getMsgByMsgKey(className, request,exMessageCode);
	}
	private String getMsgByMsgKey(String msgKey,HttpServletRequest request,String exMessageCode) {
		RequestContext requestContext = new RequestContext(request);
		return requestContext.getMessage(msgKey+"."+exMessageCode)+"["+exMessageCode+"]";
	}
}
